package com.example.gaode.location

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.location.bean.LocationInfo
import com.example.amap.location.observer.ILocationObserver
import com.example.amap.service.ILocationService
import com.example.gaode.ext.toLocationInfo

@Route(path = "/location/gaode/LocationServiceImpl")
class LocationServiceImpl : ILocationService, AMapLocationListener {
    companion object {
        private const val TAG = "LocationServiceImpl"
    }

    private var mLocationClient: AMapLocationClient? = null

    private var mLocationInfo: LocationInfo? = null

    private val observers = mutableSetOf<ILocationObserver>()

    override fun init(context: Context?) {
        try {
            mLocationClient = AMapLocationClient(context)
        } catch (exception: Exception) {
            LogUtil.e(TAG, "init mLocationClient", exception)
        }
    }

    override fun addLocationObserver(observer: ILocationObserver) {
        LogUtil.d(TAG, "addLocationObserver observer: $observer")
        observers.add(observer)
    }

    override fun removeLocationObserver(observer: ILocationObserver) {
        LogUtil.d(TAG, "removeLocationObserver observer: $observer")
        observers.remove(observer)
    }

    override fun onLocationChanged(p0: AMapLocation?) {
        mLocationInfo = p0?.toLocationInfo()
        observers.forEach { it.onLocationChanged(mLocationInfo) }
    }

    override fun init() {
        mLocationClient?.apply {
            setLocationListener(this@LocationServiceImpl)
            setLocationOption(AMapLocationClientOption().apply {
                //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
                locationPurpose = AMapLocationClientOption.AMapLocationPurpose.Transport
                //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms
                interval = 1000
                //设置是否返回地址信息（默认返回地址信息）
                isNeedAddress = true
                //设置是否允许模拟位置,默认为true，允许模拟位置
                isMockEnable = true
            })
            // 设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            stopLocation()
            startLocation()
        }
    }

    override fun getLocationInfo(): LocationInfo? = mLocationInfo
}